import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FourSum {
    public static List<List<Integer>> code(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> ret = new ArrayList<>();


        for (int i = 0; i < nums.length;) {
            int target1 = nums[i];

            for (int j = i + 1; j < nums.length;) {
                int target2 = nums[j];
                long sum = (long)target - target1 - target2;

                int left = j + 1;
                int right = nums.length - 1;
                while (left < right) {
                    if (nums[left] + nums[right] > sum) {
                        right--;
                    } else if (nums[left] + nums[right] < sum) {
                        left++;
                    } else {
                        ret.add(Arrays.asList(nums[left], nums[right], nums[i], nums[j]));
                        left++;
                        right--;

                        while (left < right && nums[left] == nums[left - 1]) {
                            left++;
                        }

                        while (left < right && nums[right] == nums[right + 1]) {
                            right--;
                        }
                    }
                }

                j++;
                while (j < nums.length && nums[j] == nums[j - 1]) {
                    j++;
                }
            }

            i++;
            while (i < nums.length && nums[i] == nums[i - 1]) {
                i++;
            }
        }

        return ret;
    }

    public static void main(String[] args) {
        FourSum.code(new int[]{1,0,-1,0,-2,2}, 0);
    }
}
